<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/17/15
 * Time: 2:45 PM
 */

namespace Plugins\BaiduSign;

use Core\PluginContainer;

class Plugin_BaiduSign
{
    private $db;

    public function __construct()
    {
        $this->db = PluginContainer::getInstance()->singletonMake("database");
        $cron = PluginContainer::getInstance()->make('cron');
        if (!empty($cron)) {
            $cron->appendTask('baidusign_dosign', 'Plugins\BaiduSign\Plugin_BaiduSign', 'doSign', 6 * 3600);
            $cron->appendTask('baidusign_doscan', 'Plugins\BaiduSign\Plugin_BaiduSign', 'doScan', 8 * 3600);
        }
    }

    public function addUser($userId, $bduss)
    {
        if(empty($this->db->first("select count(*) from plg_baidu_users where userid=$userId or bduss='$bduss'")))
            $this->db->insert("plg_baidu_users", ["userid" => $userId, "bduss" => $bduss]);
    }

    public function doSign()
    {
        $userList = $this->db->get('select * from plg_baidu_users');
        foreach ($userList as $user) {
            $date = date('Y-m-d',time());
            $tbsList = $this->db->get("select * from plg_baidu_tiebas where userid=$user->id and signtime<'$date'");
            foreach ($tbsList as $tbs) {
                if ($this->signClient($user->bduss, $tbs->tbs)) {
                    $this->db->update("plg_baidu_tiebas", ["signtime" => $date], " where id=$tbs->id");
                }
            }
        }
    }

    public function doScan(){
        $userList = $this->db->get('select * from plg_baidu_users');
        foreach ($userList as $user) {
            $this->scanUserTieba($user->userid,$user->bduss);
        }
    }


    public function scanUserTieba($userId, $bduss)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies = ["BDUSS" => $bduss];
        $curl->httpHeader=["Accept-Encoding"=>"UTF-8"];
        $response = $curl->sendRequest('http://tieba.baidu.com/f/like/mylike');
        $response = mb_convert_encoding($response,'UTF-8','gbk');
        preg_match('/href="\/f\/like\/mylike\?&pn=([0-9]+?)">尾页/', $response, $arr);
        $total = $arr[1];
        for ($i = 1; $i <= $total; $i++) {
            $response = $curl->sendRequest("http://tieba.baidu.com/f/like/mylike?&pn=$i");
            $response = mb_convert_encoding($response,'UTF-8','gbk');
            preg_match_all('/href="\/f\?kw=.*?title="(.*?)">.*?balvid="([0-9]+?)"/',$response,$arr);
            for($j=0;$j<count($arr[2]);$j++) {
                if ($this->db->first("select count(*) as c from plg_baidu_tiebas where userid=$userId and tbs='{$arr[1][$j]}'")->c > 0) {
                    $this->db->update('plg_baidu_tiebas', ["fid" => $arr[2][$i]], " where userid=$userId and tbs='{$arr[1][$j]}'");
                } else {
                    $this->db->insert('plg_baidu_tiebas', ["userid" => $userId, "fid" => $arr[2][$j], "tbs" => $arr[1][$j]]);
                }
            }
        }
    }

    private function signClient($bduss, $keyWord)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $post = [
            "BDUSS" => $bduss,
            "_client_id" => "wappc_1450343170879_531",
            "_client_type" => 2,
            "_client_version" => "6.6.2",
            "_phone_imei" => "865586024912216",
            "fid" => $this->getFID($keyWord),
            "kw" => $keyWord,
            "net_type"=>3,
            "tbs" => $this->getTBS($bduss)
        ];
        $sign = '';
        foreach ($post as $key => $value)
            $sign .= $key . '=' . $value;
        $post['sign'] = strtoupper(md5($sign . 'tiebaclient!!!'));
        $curl->formData = $post;
        $curl->method = "POST";
        $curl->httpHeader = [
            "User-Agent" => "bdtb for Android 6.6.2",
            "Content-Type" => "application/x-www-form-urlencoded",
        ];
        $response = $curl->sendRequest('http://c.tieba.baidu.com/c/c/forum/sign');
        $json = json_decode($response);
        if ($json->error_code == null || $json->error_code = 160002)
            return true;
        return "$json->error_code:$json->error_msg";
    }

    private function getTBS($bduss)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies = ['BDUSS' => $bduss];
        $curl->httpHeader = [
            "User-Agent" => "Jupiter Phone",
            "Referer" => "http://tieba.baidu.com/",
            "X-Forwarded-For" => "117.63.189." . mt_rand(1, 255)
        ];
        $response = $curl->sendRequest("http://tieba.baidu.com/dc/common/tbs");
        $curl->close();
        return json_decode($response)->tbs;

    }

    private function getFID($keyWord)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->httpHeader = [
            "User-Agent" => "Jupiter Phone",
            "Referer" => "http://wapp.baidu.com/",
            "Content-Type" => "application/x-www-form-urlencoded"
        ];
        $response = $curl->sendRequest('http://tieba.baidu.com/mo/m?kw=' . urlencode($keyWord));
        if (preg_match('/name="fid" value="(.*?)"/', $response, $arr)) {
            $curl->close();
            return $arr[1];
        }
        $curl->close();
        return '';

    }
}